<script setup>
    import blogApi from "@/api/blog.js";
    import blogTypeApi from "@/api/blogType.js";
    import WangEditor from "@/components/WangEditor.vue";
    import {ref, reactive} from "vue";
    import {
        Delete,
        Edit,
        Download,
        Upload,
    } from '@element-plus/icons-vue'
    import {ElMessage, ElMessageBox} from "element-plus";

    //表格数据
    const list = ref([])
    const total = ref(0)
    //分页信息和搜索条件
    const blogQuery = reactive({
        name: '',
        typeId: '',
        beginCreateTime: '',
        endCreateTime: '',
        page: 1,
        limit: 10
    })

    //加载所有类型
    const blogTypeList = ref([])
    const loadBlogTypeList = () => {
        blogTypeApi.selectAll().then(result => {
            blogTypeList.value = result.data
        })
    }
    loadBlogTypeList()

    const selectChange = (value) => {
        console.log(value)
    }

    const loadData = () => {
        blogApi.list(blogQuery).then(result => {
            list.value = result.data.list
            total.value = result.data.total
        })
    }

    loadData()

    /*function loadData(){
        blogApi.list(blogQuery).then(result => {
            list.value = result.data.list
            total.value = result.data.total
        })
    }*/

    /*function onSearch() {
        blogQuery.page = 1;
        loadData();
    }*/

    const onSearch = () => {
        blogQuery.page = 1;
        loadData();
    }

    //根据Id删除
    const deleteById = (id) => {
        ElMessageBox.confirm(
            '确认要删除吗？',
            '警告',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
                lockScroll: false //防止抖动
            }
        ).then(() => {
            blogApi.deleteById(id).then(result => {
                if (result.code === 0) {
                    ElMessage({message: result.msg, type: 'success',})
                } else {
                    ElMessage.error(result.msg)
                }
                loadData()
            })
        })
    }

    //批量删除
    const ids = ref([])
    const handleSelectionChange = (rows) => {
        //console.log('多选',rows);
        ids.value = rows.map(row => row.id);
        console.log(ids.value);
    }
    const deleteAll = () => {
        ElMessageBox.confirm(
            '确认要删除吗？',
            '警告',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
                lockScroll: false //防止抖动
            }
        ).then(() => {
            blogApi.deleteAll(ids.value).then(result => {
                if (result.code === 0) {
                    ElMessage({message: result.msg, type: 'success',})
                } else {
                    ElMessage.error(result.msg)
                }
                loadData()
            })
        })
    }

    //添加和修改
    const dialogFormVisible = ref(false)
    const blog = ref({})
    const title = ref()

    const showAddDialog = () => {
        dialogFormVisible.value = true
        title.value = '添加'
        blog.value = {}
    }
    const showUpdateDialog = (id) => {
        dialogFormVisible.value = true
        title.value = '编辑'
        blog.value = {}
        blogApi.selectById(id).then(result => {
            blog.value = result.data
        })
    }

    const addOrUpdate = () => {
        if (blog.value.id) {
            blogApi.update(blog.value).then(result => {
                if (result.code === 0) {
                    ElMessage({message: result.msg, type: 'success',})
                    dialogFormVisible.value = false
                } else {
                    ElMessage.error(result.msg)
                }
                loadData()
            })
        } else { //添加
            blogApi.add(blog.value).then(result => {
                if (result.code === 0) {
                    ElMessage({message: result.msg, type: 'success',})
                    dialogFormVisible.value = false
                } else {
                    ElMessage.error(result.msg)
                }
                loadData()
            })
        }
    }

    import { Plus } from '@element-plus/icons-vue'
    const handleAvatarSuccess = (result) => {
        blog.value.image = result.data
    }

    import {useTokenStore} from "@/store/token.js";
    const tokenStore = useTokenStore();
    const headers = ref({
        //添加token
        Authorization: tokenStore.token
    })

    //修改status状态
    const handleSwitchChange = (row) => {
        blogApi.updateStatus(row.id, row.status).then(result => {
            if (result.code === 0) {
                ElMessage({message: result.msg, type: 'success',})
                dialogFormVisible.value = false
            } else {
                ElMessage.error(result.msg)
            }
        })
    }

    //富文本编辑器
    const onEditorChange = (content) => {
        blog.value.content = content
    }

    //导出Excel
    const exportExcel = () => {
        blogApi.exportExcel().then(result => {
            let blob = new Blob([result], {type: "application/xlsx"});
            let url = window.URL.creatObjectURL(blob);
            const link = document.createElement("a");   //创建a标签
            link.href = url;
            link.download = "博客列表.xlsx";    //重命名文件
            link.click();
            URL.revokeObjectURL(url);
        })
    }
</script>

<template>
    <el-card class="">
        <template #header>
            <div class="header">
                <el-row>
                    <el-button type="success" :icon="Plus" @click="showAddDialog">添加</el-button>
                    <el-button type="danger" :icon="Delete" @click="deleteAll">批量删除</el-button>
                    <el-button type="primary" :icon="Download" @click="exportExcel">导出Excel</el-button>
                    <el-upload
                        method="post"
                        action="api/blog/importExcel"
                        name="file"
                        style="display:inline-block;margin-left:10px"
                        :show-file-list="false"
                        accept=".xlsx,.xls"
                        :on-success="success"
                        :headers="headers">
                        <el-button type="primary" :icon="Upload" @click="importExcel">导入Excel</el-button>
                    </el-upload>
                </el-row>

            </div>
        </template>
        <el-form :inline="true">
            <el-form-item label="博客题目">
                <el-input v-model="blogQuery.name" placeholder="请输入博客题目" clearable />
            </el-form-item>
            <el-form-item label="博客类型" @change="selectChange" style="width: 200px" :label-width="70">
                    <el-select v-model="blogQuery.typeId" placeholder="请选择类型">
                        <el-option
                            v-for="blogType in blogTypeList"
                            :key="blogType.id"
                            :label="blogType.name"
                            :value="blogType.id"/>
                    </el-select>
            </el-form-item>
            <el-form-item label="创建时间">
                <el-date-picker
                    v-model="blogQuery.beginCreateTime"
                    type="datetime"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    placeholder="开始时间"
                />
                <el-date-picker
                    v-model="blogQuery.endCreateTime"
                    type="datetime"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    placeholder="结束时间"
                />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="onSearch">搜索</el-button>
            </el-form-item>
        </el-form>

        <el-table :data="list" style="width: 100%" ref="multipleTableRef" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column fixed prop="id" label="ID" width="150" />
            <el-table-column prop="name" label="博客题目"/>
            <el-table-column prop="image" label="博客封面">
                <template #default="scope">
                    <img :src="scope.row.image" style="max-height: 40px;max-width: 120px" />
                </template>
            </el-table-column>
            <el-table-column prop="clickCount" label="点击阅读量"/>
            <!--<el-table-column prop="content" label="博客内容"/>-->
            <el-table-column prop="typeName" label="所属分类"/>
            <el-table-column prop="status" label="状态">
                <template #default="scope">
                    <el-switch
                        v-model="scope.row.status"
                        style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                        inline-prompt
                        active-text="上架"
                        inactive-text="下架"
                        :active-value="1"
                        :inactive-value="0"
                        @change="handleSwitchChange(scope.row)"
                    />
                </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间"/>
            <el-table-column prop="updateTime" label="更新时间"/>
            <el-table-column fixed="right" label="Operations" min-width="120">
                <template #default="{ row }">
                    <el-button type="primary" :icon="Edit" circle @click="showUpdateDialog(row.id)"/>
                    <el-button type="danger" :icon="Delete" circle @click="deleteById(row.id)"/>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
            v-model:current-page="blogQuery.page"
            v-model:page-size="blogQuery.limit"
            :page-sizes="[10, 20, 30, 40]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @change="loadData"
            style="margin-top: 20px; justify-content: flex-end"/>

        <!--添加、编辑的弹出框-->
        <el-dialog v-model="dialogFormVisible" :title="title" width="70%" :lock-scroll="false">
            <el-form :model="blog">
                <el-form-item label="博客题目" :label-width="70">
                    <el-input v-model="blog.name" autocomplete="off" />
                </el-form-item>
                <el-form-item label="博客类型" :label-width="70">
                        <el-select @change="selectChange" v-model="blog.typeId" placeholder="请选择类型">
                            <el-option
                                v-for="blogType in blogTypeList"
                                :key="blogType.id"
                                :label="blogType.name"
                                :value="blogType.id"/>
                        </el-select>
                </el-form-item>
                <el-form-item label="博客封面" :label-width="70">
                    <el-upload
                        class="avatar-uploader"
                        action="/api/upload"
                        :show-file-list="false"
                        :on-success="handleAvatarSuccess"
                        :headers="headers"
                    >
                        <img v-if="blog.image" :src="blog.image" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                    </el-upload>
                </el-form-item>
                <el-form-item label="博客内容" :label-width="70">
                    <WangEditor :initValue="blog.content" @getEditorContent="onEditorChange"
                    v-if="dialogFormVisible" @close="dialogFormVisible = false"/>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取消</el-button>
                    <el-button type="primary" @click="addOrUpdate">
                        确认
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </el-card>
</template>

<style scoped>
    .avatar-uploader .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }
    .avatar-uploader .el-upload {
        border: 1px dashed var(--el-border-color);
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: var(--el-transition-duration-fast);
    }

    .avatar-uploader .el-upload:hover {
        border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        text-align: center;
    }
</style>